package com.github.gaojh.mvc.filter;


import com.github.gaojh.ioc.annotation.WebFilter;
import com.github.gaojh.server.utils.PathMatcher;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author gaojianhua
 * @date 2019/12/11 3:57 下午
 */
public class FilterContext {

    private static ConcurrentHashMap<WebFilter, Filter> interceptorMap = new ConcurrentHashMap<>(128);

    public static List<Filter> getInterceptor(String path) {
        return interceptorMap.entrySet().stream()
                .filter(entry -> Arrays.stream(entry.getKey().pathPatterns()).anyMatch(pattern -> PathMatcher.path.match(pattern, path)))
                .filter(entry -> Arrays.stream(entry.getKey().ignorePathPatterns()).noneMatch(s -> PathMatcher.path.match(s, path)))
                .sorted(Comparator.comparingInt(value -> value.getKey().order()))
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());
    }

    public static void addInterceptor(WebFilter webFilter, Filter filter) {
        interceptorMap.put(webFilter, filter);
    }

}
